package com.runa.monitor.platinterface.netservice.handler;

import com.alibaba.fastjson.JSON;
import com.runa.monitor.platinterface.base.BaseContainer;
import com.runa.persistence.util.SpringContextUtil;
import com.runa.monitor.platinterface.netservice.equipment.NetEqu;
import com.runa.monitor.platinterface.platService.NetEquService;
import com.runa.persistence.util.LogUtil;
import com.runa.protocol.dto.DtuReport;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;

/**
 * @author zhuj
 */
@Slf4j
@ChannelHandler.Sharable
public class UdpReportHandler extends SimpleChannelInboundHandler<DtuReport> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, DtuReport msg) {
        log.debug("UdpReportHandler.channelRead0 msg: {}", JSON.toJSONString(msg));
        NetEquService netEquService = SpringContextUtil.getBean(NetEquService.class);
        NetEqu<String> netEqu = netEquService.getNetEquBySerial(msg.getData());
        if (netEqu != null) {
            if (msg.isMustAck()) {
                ctx.channel().writeAndFlush(msg.getAck());
            }
            if (msg.getClass().getName().contains("Report")) {
                netEqu.register(ctx.channel());
                BaseContainer.netStatusCallback().rccStatusChange(msg.getData(), true);
            }
        } else {
            log.debug("UDP非法客户端: {} 尝试连接.", msg.getData());
        }
    }

}
